package com.yxq.mdt.app.modules.spike.ui;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.blankj.utilcode.util.ToastUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.application.IntentHelper;
import com.yxq.mdt.app.base.BaseActivity;
import com.yxq.mdt.app.constant.RouteTable;
import com.yxq.mdt.app.modules.spike.bean.SpikeBean;
import com.yxq.mdt.app.modules.spike.bean.SpikeGoodsBean;
import com.yxq.mdt.app.modules.spike.model.SpikeModel;
import com.yxq.mdt.app.modules.spike.prestener.ISpikeContract;
import com.yxq.mdt.app.modules.spike.prestener.SpikePresenter;
import com.yxq.mdt.app.utils.GridSpacingItemDecoration;

import net.lucode.hackware.magicindicator.FragmentContainerHelper;
import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.CommonPagerTitleView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * @author L
 * @time
 * @describe 秒杀首页
 */
@Route(path = RouteTable.ROUTER_ACTIVITY_SPIKE)
public class SpikeHomeActivity extends BaseActivity<SpikePresenter> implements ISpikeContract.View {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.magic_indicator)
    MagicIndicator magicIndicator;
    List<SpikeBean.ListBeanX> titleList;
    SpikeGoodsListAdapter spikeGoodsListAdapter;
    int currentItem = 0;//当前选中的Tab

    @Override
    public int getLayoutId() {
        return R.layout.activity_spike_home;
    }

    @Override
    public void initView() {
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(refreshLayout -> refresh());
        mCommonTitleBar.getCenterTextView().getPaint().setFakeBoldText(true);//加粗
        mPresenter = new SpikePresenter(this, new SpikeModel());
        mPresenter.list();
    }

    /**
     * 下拉刷新数据
     */
    private void refresh() {
        //查询第一场的商品数据
        if (titleList != null && titleList.size() > 0) {
            mPresenter.goodsList(titleList.get(currentItem).getStart_time(), 1);
        }else{
            refreshLayout.finishRefresh();
        }
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        spikeGoodsListAdapter = new SpikeGoodsListAdapter(R.layout.layout_spike_goods_item_layout, null);
        recyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        recyclerView.setAdapter(spikeGoodsListAdapter);
        spikeGoodsListAdapter.setEmptyView(R.layout.layout_empty_view, recyclerView);
        spikeGoodsListAdapter.isUseEmpty(false);
        spikeGoodsListAdapter.setOnItemClickListener((adapter, view, position) -> {
            //跳转商品详情
            Bundle bundle = new Bundle();
            bundle.putString("id", spikeGoodsListAdapter.getData().get(position).getId());
            IntentHelper.arouter(RouteTable.ROUTER_ACTIVITY_SPIKE_GOODS_DETAIL, bundle);
        });
        recyclerView.addItemDecoration(new GridSpacingItemDecoration(1, 40, false));
    }

    @Override
    public void onLoadListSuccess(SpikeBean spikeBean) {
        if (spikeBean == null) {
            return;
        }
        initView(spikeBean);
        refreshLayout.autoRefresh();
    }

    @Override
    public void onLoadListFailed(String err) {
        ToastUtils.showShort(err);
    }

    @Override
    public void onLoadGoodsListSuccess(SpikeGoodsBean spikeGoodsBean) {
        refreshLayout.finishRefresh();
        spikeGoodsListAdapter.setNewData(spikeGoodsBean.getList());
        spikeGoodsListAdapter.isUseEmpty(!(spikeGoodsListAdapter.getData().size() > 0));
    }

    @Override
    public void onLoadGoodsListFailed(String err) {
        ToastUtils.showShort(err);
        refreshLayout.finishRefresh();
    }

    /**
     * 抢购场次
     *
     * @param spikeBean
     */
    private void initView(SpikeBean spikeBean) {
        titleList = new ArrayList<>();
        for (SpikeBean.ListBeanX beanX : spikeBean.getList()) {
            if (beanX.getStatus() != 0) {
                titleList.add(beanX);
            }
        }
        if (titleList.size() == 0) {
            return;
        }
        //初始化场次列表菜单
        FragmentContainerHelper mFragmentContainerHelper = new FragmentContainerHelper();
        CommonNavigator commonNavigator = new CommonNavigator(this);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {

            @Override
            public int getCount() {
                return titleList.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {

                CommonPagerTitleView commonPagerTitleView = new CommonPagerTitleView(mActivity);
                commonPagerTitleView.setContentView(R.layout.layout_magicindicator_spike_item_layout);

                // 初始化
                final TextView titleTitle = commonPagerTitleView.findViewById(R.id.indicator_tv_title);
                titleTitle.setText(titleList.get(index).getTitle());
                final TextView titleText = commonPagerTitleView.findViewById(R.id.indicator_tv_sub);
                titleText.setText(titleList.get(index).getStatus_text());
                LinearLayout bgView = commonPagerTitleView.findViewById(R.id.indicator_bg);
                if (index == currentItem) {
                    //选中
                    bgView.setBackgroundResource(R.drawable.shape_indicator_red_bg);
                } else {
                    bgView.setBackgroundResource(R.drawable.shape_indicator_black_bg);
                }
                commonPagerTitleView.setOnPagerTitleChangeListener(new CommonPagerTitleView.OnPagerTitleChangeListener() {

                    @Override
                    public void onSelected(int index, int totalCount) {
                        titleText.setTextColor(Color.WHITE);
                    }

                    @Override
                    public void onDeselected(int index, int totalCount) {
                        titleText.setTextColor(Color.WHITE);
                    }

                    @Override
                    public void onLeave(int index, int totalCount, float leavePercent, boolean leftToRight) {
//                        titleTitle.setScaleX(1.3f + (0.8f - 1.3f) * leavePercent);
//                        titleTitle.setScaleY(1.3f + (0.8f - 1.3f) * leavePercent);
                    }

                    @Override
                    public void onEnter(int index, int totalCount, float enterPercent, boolean leftToRight) {
//                        titleTitle.setScaleX(0.8f + (1.3f - 0.8f) * enterPercent);
//                        titleTitle.setScaleY(0.8f + (1.3f - 0.8f) * enterPercent);
                    }
                });

                commonPagerTitleView.setOnClickListener(v -> {
                    currentItem = index;
                    mFragmentContainerHelper.handlePageSelected(index);

                    notifyDataSetChanged();
                    refreshLayout.autoRefresh();
                });

                return commonPagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {

                return null;
            }
        });
        magicIndicator.setNavigator(commonNavigator);
        mFragmentContainerHelper.attachMagicIndicator(magicIndicator);
    }
}
